﻿using System.Transactions;
using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.WriteApi.Application.Command.Users;
using MD5Hash;
using MediatR;

namespace BaseData.WriteApi.Application.CommandHandler.Users
{
    /// <summary>
    /// 处理插入用户命令的命令处理器
    /// </summary>
    public class InsertUserCommandHandler : IRequestHandler<InsertUserCommand, Apiresult<int>>
    {
        private readonly IBasepository<UserInfo> userpository;  // 用户信息仓储接口
        private readonly IBasepository<Role> rolepository;  // 角色仓储接口
        private readonly IBasepository<UserRole> uRpository;  // 用户角色仓储接口
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IBasepository<RolePermiss> rolePerpository;  // 角色权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<InsertUserCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数，注入所需的服务
        /// </summary>
        /// <param name="_userpository">用户信息仓储</param>
        /// <param name="_rolepository">角色仓储</param>
        /// <param name="_URpository">用户角色仓储</param>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_rolePerpository">角色权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public InsertUserCommandHandler(
            IBasepository<UserInfo> _userpository,
            IBasepository<Role> _rolepository,
            IBasepository<UserRole> _URpository,
            IBasepository<Permission> _permisspository,
            IBasepository<RolePermiss> _rolePerpository,
            IMapper _mapper,
            ILogger<InsertUserCommandHandler> _logger)
        {
            userpository = _userpository;
            rolepository = _rolepository;
            uRpository = _URpository;
            permisspository = _permisspository;
            rolePerpository = _rolePerpository;
            mapper = _mapper;
            logger = _logger;
        }

        /// <summary>
        /// 处理插入用户命令
        /// </summary>
        /// <param name="request">插入用户的请求数据</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>返回操作结果</returns>
        public async Task<Apiresult<int>> Handle(InsertUserCommand request, CancellationToken cancellationToken)
        {
            // 开启事务处理
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 将请求数据映射为用户信息对象
                    var user = new UserInfo()
                    {
                        UserName = request.UserName,
                        UserEmail = request.UserEmail,
                        NickName = request.NickName,
                        Password = request.Password.GetMD5()
                    };
                    // 插入用户数据
                    var res = await userpository.InsertAsync(user);
                    if (res > 0)
                    {
                        // 查找角色信息
                        var role = await rolepository.GetModel(r => r.RoleId == request.RoleId);
                        if (role != null)
                        {
                            // 创建用户角色关联数据
                            UserRole ur = new UserRole
                            {
                                UserId = user.UserId,
                                RoleId = role.RoleId
                            };
                            // 插入用户角色数据
                            var rres = await uRpository.InsertAsync(ur);
                            if (rres > 0)
                            {
                                // 提交事务
                                tran.Complete();
                                return new Apiresult<int>
                                {
                                    Code = ResultCode.添加成功,
                                    Message = "用户添加成功"
                                };
                            }
                            else
                            {
                                // 插入用户角色失败，回滚事务
                                tran.Dispose();
                                return new Apiresult<int>
                                {
                                    Code = ResultCode.添加失败,
                                    Message = "用户角色添加失败",
                                };
                            }
                        }
                        else
                        {
                            // 如果角色不存在，回滚事务
                            tran.Dispose();
                            return new Apiresult<int>
                            {
                                Code = ResultCode.添加失败,
                                Message = "角色不存在，用户添加失败"
                            };
                        }
                    }
                    else
                    {
                        // 插入用户失败，回滚事务
                        tran.Dispose();
                        return new Apiresult<int>()
                        {
                            Code = ResultCode.添加失败,
                            Message = "用户添加失败"
                        };
                    }
                }
                catch (Exception ex)
                {
                    // 发生异常时，回滚事务
                    tran.Dispose();
                    // 记录日志
                    logger.LogError($"InsertUserCommandHandler.Handle方法异常：{ex.Message},{ex.StackTrace}");
                    return new Apiresult<int>
                    {
                        Code = ResultCode.添加失败,
                        Message = "系统异常，用户添加失败"
                    };
                }
            }
        }
    }
}
